<template>
  <div>
    <label> {{ label }} </label>
    <div>
      <slot></slot>
    </div>
    <p v-if="errorMsg" > {{ errorMsg }} </p>
  </div>
</template>
<script>
import AsyncValidate from 'async-validator'
export default {
  name: 'LgFormItem',
  inject: ['form'],
  props:{
    label: {
      type: String
    },
    prop:{
      type: String
    }
  },
  mounted() {
    this.$on('validate', ()=>{ // 给form item 注册 validat 事件
      this.validate()
    })
  },
  data(){
    return{
      errorMsg: ''
    }
  },
  methods:{
    validate(){
      if(!this.prop) return
      const value = this.form.model[this.prop]
      const rules = this.form.rules[this.prop]
      // 通过AsyncValidate，根据当前元素设定的规则验证元素传入的值
      const descriptor = { [this.prop]: rules}
      const validator = new AsyncValidate(descriptor)
      return validator.validate({ [this.prop]: value }, errors=>{
        console.log('validate errors', {errors})
        this.errorMsg = errors ? errors[0].message : ''
      })
    }
  }
}
</script>